package com.tos.second.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.tos.second.common.Result.Result;
import com.tos.second.common.constant.MessageConstant;
import com.tos.second.common.exception.BaseException;
import com.tos.second.entity.User;
import com.tos.second.utils.AliOssUtil;
import com.tos.second.utils.MailMsg;
import com.tos.second.utils.MailUtils;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MailMsg mailMsg;


    /**
     * 发送验证码接口
     *
     * @param user
     * @param
     * @return
     */
    @PostMapping("/sendCode")
    public Result<String> sendCode(@RequestBody User user) {
        String email = user.getEmail();
        log.info("发送验证码：{}", email);
        // 生成验证码
        if (!email.isEmpty()) {
            // 生成验证码
            String code = MailUtils.achieveCode();
//            String code = "1234";
            log.info("验证码为：{}", code);
            // 发送邮件
            try {
                mailMsg.mail(email, code);
            }  catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.success();
    }

    /**
     * 上传照片接口
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BaseException("文件不能为空");
        }
        log.info("文件上传：{}", file.getOriginalFilename());
//        String originalFilename = file.getOriginalFilename();
//        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        try {
//            String path = "C:/Users/z1378/Desktop/second-images/" + fileName;
//            file.transferTo(new File(path));
//            // 返回前端值
//            return Result.success(path);
//        } catch (IOException e) {
//            throw new BaseException("上传失败");
//        }
        try {
            String path = aliOssUtil.upload(file);
            return Result.success(path);
        } catch (IOException e) {
            log.info("文件上传失败，{}", e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        //return Result.error(MessageConstant.UPLOAD_FAILED);
    }


//    /**
//     * jdk1.8使用
//     * @return
//     */
//    @GetMapping("/checkCode")
//    public Result<Map<String,String>> checkCode() {
//        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
//        String code = captcha.text();
//        String checkCodeKey = UUID.randomUUID().toString();
//        log.info("验证码：{}", code);
//        redisTemplate.opsForValue().set(MessageConstant.REDIS_KEY_CHECK_CODE + checkCodeKey, code, 600L, TimeUnit.SECONDS);
//        String base64 = captcha.toBase64();
//        Map<String, String> result = new HashMap<>();
//        result.put("checkCode", base64);
//        result.put("checkCodeKey", checkCodeKey);
//        return Result.success(result);
//    }


    @GetMapping("/")
    public ResponseEntity<Void> index() {
        return ResponseEntity.status(302).header("Location", "/static/image-test.html").build();
    }

    @RequestMapping("/code")
    public Result<Map<String,String>> getCode() {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        // 获取验证码内容（即验证码的文本）
        String captchaCode = lineCaptcha.getCode();

        // 创建一个 ByteArrayOutputStream，用于将图像写入内存
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        // 将验证码图像写入 ByteArrayOutputStream
        lineCaptcha.write(byteArrayOutputStream);

        // 将字节流转换为 Base64 编码字符串
        String base64Captcha = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());

        // 生成一个唯一的验证码 key
        String checkCodeKey = UUID.randomUUID().toString();

        // 将验证码内容存储到 Redis，设置过期时间（例如5分钟）
        redisTemplate.opsForValue().set(MessageConstant.REDIS_KEY_CHECK_CODE + checkCodeKey, captchaCode, 1, TimeUnit.MINUTES);

        // 输出 Base64 编码的验证码
        log.info("验证码：{}", captchaCode);
        Map<String,String> map = new HashMap<>();
        map.put("checkCodeKey",checkCodeKey);
        map.put("base64Captcha",base64Captcha);
        // 返回 Base64 编码的验证码图片以及存储验证码的 key
        return Result.success(map);
    }
}
